<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Support\Facades\Cache;
use App\Services\BuyGoldCash\BuyGoldCash;
use App\Http\Controllers\Api\V1\Queries\GoldCashQuery;
use App\Http\Controllers\Api\V1\Requests\BuyGoldCashRequest;

class GoldCashesController extends Controller
{
    public function index(GoldCashQuery $query): array
    {
        $user = request()->user();
        $condition = request('condition');
        $query = $query->where('user_id', $user->id);
        $query = !empty(request('start_time')) ? $query->where('created_at', '>', request('start_time')) : $query;
        $query = !empty(request('end_time')) ? $query->where('created_at', '<', request('end_time')) : $query;

        $total = $query->inquire($condition)->sum('money');
        $beans = $query->inquire($condition)->orderByDesc('id')->paginate();

        return ['total' => $total, 'data' => $beans];
    }

    public function buy()
    {
        $lock = Cache::lock('cashes_buying', 15);

        try {

            if (! $lock->get()) fail('处理中...请勿频繁操作');

            $request = app(BuyGoldCashRequest::class);

            $user = $request->user();

            need_paycode($user);

            app(BuyGoldCash::class, [
                'user' => $user,
                'beans' => $request->beans,
                'payCode' => $request->pay_code,
            ])->buy();

            $user->resetPayCodeTry();

            return response(null, 204);

        } finally {
            $lock->release();
        }
    }

	public function transfer()
	{
        fail('Cancelled');

		/*$lock = Cache::lock('cashes_transfer', 15);

		try {

			if (! $lock->get()) fail('处理中...请勿频繁操作');

			$request = app(TransferGoldCashRequest::class);

			$user = $request->user();

			need_paycode($user);

			app(TransferGoldCash::class, [
				'self' => $user,
				'child' => $request->getChild(),
				'cashes' => $request->amount,
				'payCode' => $request->pay_code,
			])->apply();

			$user->resetPayCodeTry();

            return response(null, 204);

		} finally {
			$lock->release();
		}*/
	}
}
